<?php
	require_once dirname(BASEPATH) . '/application/models/local/data/_init_model.php';
	
	class mod_p_rate_record extends _init_model
	{
		public $P_RATE_RC_ID;
		public $P_RATE_RC_SCORE;
		public $CAF_PDT_ID;
		public $CAF_ID;
		public $MEM_ID;
		
		function __construct(){
			parent::__construct();
						
			$this->tableName = 'p_rate_record';
		}
		
		function rate($product_id, $member_id, $cafe_id, $score){
			$this->db->where(array('CAF_PDT_ID' => $product_id,
									'MEM_ID' => $member_id));
			$count = $this->db->count_all_results($this->tableName);

			$this->P_RATE_RC_SCORE = $score;
			$this->CAF_PDT_ID = $product_id;
			$this->CAF_ID = $cafe_id;
			$this->MEM_ID = $member_id;
			if ($count > 0)
				return $this->edit($product_id, $member_id);
			else
				return $this->add();
		}		
		function get_rate_record_of_member($product_id, $member_id){
			$this->db->select('P_RATE_RC_SCORE');
			$this->db->where(array('MEM_ID' => $member_id,
									'CAF_PDT_ID' => $product_id));
			$query = $this->db->get($this->tableName);
			if ($query->num_rows() > 0)
				return $query->row(0)->P_RATE_RC_SCORE;
			else 
				return 0;
		}
		function get_rate_count($cafe_id, $product_id){
			$sqlcmd = 'SELECT COUNT(*) AS R_COUNT';
			$sqlcmd .= ' FROM ' . $this->tableName;
			$sqlcmd .= ' WHERE CAF_PDT_ID = ' . $product_id;
			$sqlcmd .= ' AND CAF_ID = ' . $cafe_id;

			$query = $this->db->query($sqlcmd);
			return $query->row()->R_COUNT;
		}
		
		function add(){
			return $this->db->insert($this->tableName, array('P_RATE_RC_SCORE' => $this->P_RATE_RC_SCORE,
																'CAF_PDT_ID' => $this->CAF_PDT_ID,
																'CAF_ID' => $this->CAF_ID,
																'MEM_ID' => $this->MEM_ID));
		}
		function edit($product_id, $member_id){
			$data = array();
			if (!empty($this->P_RATE_RC_SCORE))
				$data['P_RATE_RC_SCORE'] = $this->P_RATE_RC_SCORE;

			$this->db->where(array('CAF_PDT_ID' => $this->CAF_PDT_ID,
									'MEM_ID' => $this->MEM_ID));
			return $this->db->update($this->tableName, $data);
		}
		function remove_by_product_in($data){			
			$this->db->where_in('CAF_PDT_ID', $data);
			return $this->db->delete($this->tableName);
		}
		function remove_by_product($product_id){
			$this->db->where('CAF_PDT_ID', $product_id);
			return $this->db->delete($this->tableName);
		}
	}
?>